const {
  studentRegister,
  getPhoneNumber,
  getUserProfile,
  educationalExperience
} = require('../../../../api/index');
const {
  getBatchDict
} = require('../../../../utils/dict');
const WXBizDataCrypt = require('../../../../utils/WXBizDataCrypt');

const {
  validate
} = require('../../../../utils/util');

// pages/authentication/index/index.js
Page({
  data: {
    selectSchool: 'addExperience2',
    isSelectImage: false,
    type: '',
    index: 0,
    educationDicts: [],
    genderDicts: [],
    yearDicts: [],
    cityDicts: [],
    formData: {
      locations: [], //  缓存 省市
      schoolName: "",
      department: "",
      major: "",
      education: "",
      locationProvince: "",
      locationCity: "",
      enrollmentYear: "",
      educationPhoto: ''
      // phone: ""
    },
    errors: {},
    rules: {
      schoolName: [{
        empty: true,
        msg: '学校名不能为空'
      }],
      department: [{
        empty: true,
        msg: '院系不能为空'
      }],
      major: [{
        empty: true,
        msg: '专业不能为空'
      }],
      education: [{
        empty: true,
        msg: '学历不能为空'
      }],
      locations: [{
        empty: true,
        msg: '所在省市不能为空'
      }],
      enrollmentYear: [{
        empty: true,
        msg: '入学时间不能为空'
      }],
      educationPhoto: [{
        empty: true,
        msg: '材料截图不能为空'
      }]
    }
  },
  onShow() {
    const _data = this.data.formData;
    const collegeName = wx.getStorageSync(this.data.selectSchool)?.collegeName;
    collegeName && (_data.schoolName = collegeName);
    _data.educationName = this.data.educationDicts.find(_s => _s.code === _data.education)?.name;
    if (_data.locations.length > 0) {
      _data.locationName = _data.locations[0] + '/' + _data.locations[1];
    } else {
      _data.locationName = '';
    }

    this.setData({
      formData: JSON.parse(JSON.stringify(_data))
    });
  },
  onSelectImage() { //  选择图片
    this.data.isSelectImage = true;
  },
  onUnload() {
    wx.removeStorageSync(this.data.selectSchool);
  },
  //  页面跳转
  onJump(event) {
    const {
      url
    } = event.currentTarget.dataset;
    wx.navigateTo({
      url
    });
  },
  //  修改表单数据
  onFormData(event) {
    const {
      prop
    } = event.currentTarget.dataset;
    this.data.formData[prop] = event.detail;
  },
  // 提交数据
  async onSubmit(event) {
    const error = validate(this.data.formData, this.data.rules);
    if (error) { //  如果报错就不允许进行数据的提交
      this.setData({
        errors: error
      });
      return;
    }

    const _data = setResult(JSON.parse(JSON.stringify( this.data.formData )));

    //  educationalExperienceList  将参数保存起来 缓存起来，
    addEducationalExperienceList.call(this, _data);
    //  填写完成之后 返回到上一页
    wx.navigateBack();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    //  设置年份下拉框的数据
    const yearSelect = this.selectComponent('#define-select');
    yearSelect.setActions(getYearDicts());



    //  处理字典项
    await fetchDict.call(this);

        //  设置城市  用于测试
        const citySelect = this.selectComponent('#city-select');
        citySelect.setActions( this.data.cityDicts );

    const {
      type,
      index
    } = options;
    this.data.type = type;

    if (type === 'edit') {
      //  获取 缓存的数据 - 将缓存的数据进行回显
      this.setData({ formData: getResult.call(this, index) });
    }
  }
})

//  获取并设置字典项
async function fetchDict() {
  const [ educationDicts = [], genderDicts = [], cityDicts = [] ] = await getBatchDict(
    ['EDUCATION', 'GENDER', { 
      pageNumber: 1,
      pageSize: 50,
      dictName: "XZQH",
      codeLike: "%0000" } 
    ]);

  this.data.educationDicts = educationDicts;
  this.data.genderDicts = genderDicts;
  this.data.cityDicts = cityDicts.map(item => {
    item.text = item.name;
    item.value = item.code;
    return item;
  });
}

//  处理回显数据
function getResult(index) {
  const res = wx.getStorageSync('educationalExperienceList')[index];

  res.locations = [ res.locationProvince, res.locationCity ];
  res.locationName = res.locationProvince + '/' + res.locationCity;
  res.educationName = this.data.educationDicts.find(_s => _s.code === res.education).name;
  return res;
}

//  处理表单数据
function setResult(data) {
  const _data = JSON.parse(JSON.stringify(data));
  _data.locationProvince = _data.locations[0];
  _data.locationCity = _data.locations[1];

  return _data;
}

// 获取年份列表 从 当前年份开始向下，去 150年
function getYearDicts() {
  const dicts = [];
  const curYear = new Date().getFullYear();
  for (let i = curYear; i >= curYear - 150; i--) {
    const d = String(i);
    dicts.push({
      name: d + '年',
      code: d
    })
  }

  return dicts;
}


//  将数据添加到缓存数组
function addEducationalExperienceList(data) {
  //  获取缓存中之前保存的数据
  const _data = wx.getStorageSync('educationalExperienceList') || [];

  if (this.data.type === 'edit') {
    _data[this.data.index] = data;
    wx.setStorageSync('educationalExperienceList', _data);
  } else {
    //  判断数组中是否存在该元素
    if (_data.find(_s => _s.schoolName === data.schoolName && _s.education === data.education)) {
      wx.showToast({
        title: '该信息已存在',
        icon: 'error',
        duration: 1000
      })
    } else {
      _data.push(data);
      wx.setStorageSync('educationalExperienceList', _data);
    }
  }
}